package com.bot.rf.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.bot.rf.util.MyLogger.LOGGER;

/**
 * @program: report-form-demo
 * @description: 压缩文件工具类
 * @author: zyy
 * @create: 2021-02-24 14:44
 **/
public class ZipUtil {

    /**
     *  压缩文件
     * @param inputFileName  被压缩的文件
     * @param outputFileName 生成的压缩文件
     * @throws Exception
     */
    public static void zip(String inputFileName, String outputFileName)throws Exception{
        File inputFile = new File(inputFileName);
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
        LOGGER.info(inputFileName + "压缩中...");
        zipCommon(out, inputFile, inputFile.getName());
        LOGGER.info(outputFileName + "压缩完成...");
        out.close();
    }

    /**
     * 压缩文件
     * @param inputFileNames 被压缩的文件
     * @param outFileName    生成的压缩文件
     * @throws Exception
     */
    public static void zip(List<String> inputFileNames, String outFileName)throws Exception{
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFileName));
        for (String inputFileName: inputFileNames) {
            File inputFile = new File(inputFileName);
            LOGGER.info(inputFile + "压缩中...");
            zipCommon(out, inputFile, inputFile.getName());
        }
        LOGGER.info(outFileName + "压缩完成...");
    }

    /**
     * 基本压缩方法
     * @param out
     * @param f
     * @param base
     * @throws Exception
     */
    public static void zipCommon(ZipOutputStream out, File f, String base)throws Exception{
        // 文件夹
        if (f.isDirectory()){
            File[] files = f.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : "/";
            for (int i = 0; i < files.length; i++ ) {
                zipCommon(out,files[i], base + files[i]);
            }
        }else{
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            int b;
            while ((b = in.read()) != -1){
                out.write(b);
            }
            in.close();
        }
    }
}
